﻿using MediatR;
using MySqlX.XDevAPI.Common;
using Sale.Api.Application.Command.SaleOrder;
using Sale.Domain;
using Sale.Dtos;
using Sale.ErrorCode;
using Sale.Infrastructure.Interface;

namespace Sale.Api.Application.Handler.SaleOrder
{
    public class GetSaleOrderHandler : IRequestHandler<GetSaleOrderCommand, ApiResult<List<SaleOrderDTO>>>
    {
        IBaseRepository<SalesOrderModel> saleRepo;
        IBaseRepository<ClientModel> clientRepo;
        IBaseRepository<ContractModel> conRepo;

        public GetSaleOrderHandler(IBaseRepository<SalesOrderModel> saleRepo, IBaseRepository<ClientModel> clientRepo, IBaseRepository<ContractModel> conRepo)
        {
            this.saleRepo = saleRepo;
            this.clientRepo = clientRepo;
            this.conRepo = conRepo;
        }

        public Task<ApiResult<List<SaleOrderDTO>>> Handle(GetSaleOrderCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<SaleOrderDTO>> result = new ApiResult<List<SaleOrderDTO>>();
            var sale = saleRepo.GetAll().Where(c => !c.IsDel);
            var client=clientRepo.GetAll().Where(c=>!c.IsDel);
            var contract = conRepo.GetAll().Where(c => !c.IsDel);
            var linq = from a in sale
                       join b in client on a.ClientId equals b.ClientId
                       join c in contract on a.ContractId equals c.ContractId
                       select new SaleOrderDTO
                       {
                           SalesOrderId=a.SalesOrderId,
                           SalesOrderCode=a.SalesOrderCode,
                           ContractId=c.ContractId,
                           ContractCode=c.ContractCode,
                           ContractName=c.ContractName,
                           ClientId=b.ClientId,
                           ClientCode=b.ClientCode,
                           ClientName= b.ClientName,
                           CTypeId= b.CTypeId,
                           SaleNumder=a.SaleNumder
                       };
            result.Msg = "查询销售单成功";
            result.Code = ApiEnum.OK;
            result.Data=linq.ToList();
            return Task.FromResult(result);
        }
    }
}
